package com.lg.concurrent.schedule;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;


/**
 *
 *  可以在任何一个线程中执行 LockSupport.park() 挂起这个线程
 *
 *  在任何线程中 LockSupport.unpark(otherThread); 唤醒另外的线程，多次唤醒其他线程 或者说 唤醒一个醒着的/已经死了的线程，都不会报错
 *
 *
 */
public class ParkUnpark {
    private static Thread thread;
    public static void main(String[] args) {

        thread =  new Thread(() -> {
            boolean flag = true;
            while (true) {
                try {
                    System.out.println("thread run");
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (flag) {
                    System.out.println("thread park");
                    LockSupport.park();
                    flag = false;
                }

            }
        });
        thread.start();
        System.out.println("main start sleep");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main unpark");
        LockSupport.unpark(thread);

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main unpark2");
        LockSupport.unpark(thread);
    }
}
